#include <amdgpumonitor.h>
#include <QProcess>
#include <fstream>
#include <string>
#include <filesystem>
#include <tuple>

AMDGpuMonitor::AMDGpuMonitor()
{
    find_amdgpu_path();
}

void AMDGpuMonitor::find_amdgpu_path()
{
    gpu_dev_path.clear();

    for (const auto& entry : std::filesystem::directory_iterator("/sys/class/drm"))
    {
            const std::string card_name = entry.path().filename();
            if (card_name.find("card") == 0)
            {   // 检查是否是card设备
                std::string vendor_path = entry.path().string() + "/device/vendor";
                std::ifstream vendor_file(vendor_path);
                if (vendor_file.is_open())
                {
                    std::string vendor_id;
                    vendor_file >> vendor_id;
                    if (vendor_id == "0x1002")
                    {   // AMD的厂商ID
                        gpu_dev_path = entry.path().string() + "/device";
                        break;
                    }
                }
            }
    }
}




double AMDGpuMonitor::getGpuCoreUsage()
{
    const std::string usage_file_path = gpu_dev_path + "/gpu_busy_percent";
    std::ifstream file(usage_file_path);
    if (file.is_open() == false)
    {
        return 0;
    }
    double usage;
    file >> usage;
    return usage;
}

double AMDGpuMonitor::getGpuMemUsage()
{
    double vram_total = 0;
    double vram_used = 0;
    double usage = 0;

    std::ifstream total_file(gpu_dev_path + "/mem_info_vram_total");
    if (total_file.is_open()) {
        total_file >> vram_total;
    }
    std::ifstream used_file(gpu_dev_path + "/mem_info_vram_used");
    if (used_file.is_open()) {
        used_file >> vram_used;
    }
    usage = (vram_used / vram_total) * 100;

    return usage;
}
